package com.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.beans.AdminInfo;
import com.dao.AdminDao;
import com.utils.Des;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	

	
	private AdminDao _adminDao=new AdminDao();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		String flag = request.getParameter("flag");

		if ("login".equals(flag)) {
			this.login(request, response);
		}else if("logout".equals(flag)){
			this.logOut(request,response);
		}
		
		
	}
	//用户登录
	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String adminName=request.getParameter("adminName");
		String password=request.getParameter("password");
		
		AdminInfo admin=_adminDao.login(adminName,Des.encStr(password));
		if(admin!=null) {
			if(admin.getState().equals("0")) {
				request.setAttribute("msg", "该用户被锁定，无法登陆");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}else if(admin.getState().equals("2")) {
				request.setAttribute("msg", "该用户已删除");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}else if(admin.getState().equals("1")){
				request.getSession().setAttribute("session_admin", admin);
				request.getRequestDispatcher("/main.jsp").forward(request, response);
			}
			
		}
		else {
			request.setAttribute("msg", "账号或密码错误");
			request.setAttribute("adminName", adminName);
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
		
		
	}

	//用户退出(注销)
		private void logOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
			request.getSession().invalidate();
			response.getWriter().print("1");
		}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
